<script setup lang="ts">
import { ref, PropType, toRef, watch, onUnmounted, onMounted } from "vue";
import { Setting, VideoPlay } from "@element-plus/icons-vue";
import { ContorDevice } from "@/api/LabInstanceApi";
import contordialog from "./ContorDialog.vue";
import { Experiment } from "@/api/LabExperimentApi";
import { changeOpening, ChangeSvDC1000 } from "@/api/deviceApi";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { listDeviceStatus } from "@/api/deviceApi";

const props = defineProps({
  controlList: {
    type: Array as PropType<ContorDevice[]>,
    default: () => []
  },
  expData: {
    type: Object as PropType<Experiment>,
    default: () => {}
  }
});

const controlListRef = toRef(props, "controlList");
// console.log("controlListRef1", controlListRef.value);
const emit = defineEmits([
  "update:controlList",
  "data-confirm-click",
  "delete-item"
]);
const tempControl = ref<ContorDevice>({});

const contorDialogVisible = ref(false);
let timer = null;

const clickSetting = (sensor, index) => {
  tempControl.value = JSON.parse(JSON.stringify(sensor));
  // console.log("tempControl=sensor");
  contorDialogVisible.value = true;
};

const clickRun = sensor => {
  ElMessageBox.confirm("是否确定调整控制器参数", "提示", { type: "warning" })
    .then(async () => {
      if (sensor.model == "HnwDC1000") {
        const res = await ChangeSvDC1000({
          deviceId: sensor.deviceId,
          val: sensor.temperature
        });
        if (res.errorCode === 0) {
          fectchData();
          emit("data-confirm-click");
          message("调整成功", { type: "success" });
        } else {
          message(res.message, { type: "error" }); // 显示错误消息
        }
      } else if (sensor.model == "Valve") {
        const res = await changeOpening({
          deviceId: sensor.deviceId,
          val: sensor.opening
        });
        if (res.errorCode === 0) {
          fectchData();
          emit("data-confirm-click");
          message("调整成功", { type: "success" });
        } else {
          message(res.message, { type: "error" }); // 显示错误消息
        }
      }
    })
    .catch(() => {});
};

const fectchData = () => {
  controlListRef.value.forEach(async (item, index) => {
    if (item.model == "HnwDC1000") {
      // const res = await getConfigDC1000(item.deviceId);
      const res = await listDeviceStatus();

      const displayVal = res.data.find(
        obj => obj.deviceId == item.deviceId
      ).displayVal;

      // console.log("HnwDC1000", displayVal);

      controlListRef.value[index].nowTemp = displayVal;
      if (res.errorCode === 0) {
        // message("调整成功", { type: "success" });
      } else {
        message(res.message, { type: "error" }); // 显示错误消息
      }
    } else if (item.model == "Valve") {
      const res = await listDeviceStatus();

      const displayVal = res.data.find(
        obj => obj.deviceId == item.deviceId
      ).displayVal;

      // console.log("Valve", displayVal);
      // const res = await getConfigDC1000(item.deviceId);
      controlListRef.value[index].nowOpening = displayVal;
      if (res.errorCode === 0) {
        // message("调整成功", { type: "success" });
      } else {
        message(res.message, { type: "error" }); // 显示错误消息
      }
    }
  });
  // emit("data-confirm-click");
};

const setTimer = () => {
  // clearInterval(timer);
  // timer = null;
  fectchData();
};

onMounted(() => {
  //遍历controlListRef中的deviceId
  //请求后端获取当前开度
  controlListRef.value = JSON.parse(JSON.stringify(props.controlList));
  fectchData();
  timer = setInterval(setTimer, 5000);
});

onUnmounted(() => {
  if (timer) {
    // console.log("clearInterval");
    clearInterval(timer);
    timer = null;
  }
});

// beforeUnmount(() => {
//   clearInterval(timer);
// });

const changeVal = val => {
  // console.log("val", val);
};

watch(
  () => controlListRef,
  newVal => {
    emit("update:controlList", JSON.parse(JSON.stringify(newVal)));
  }
);
</script>

<template>
  <!-- {{ controlListRef }}
  <div /> -->
  <!-- {{ tempControl }} -->

  <!-- {{ controlList }} -->
  <el-card
    class="box-card"
    style="margin: 0 10px"
    v-for="(sensor, index) in controlListRef"
    :key="index"
  >
    <!-- {{ sensor }} -->
    <template #header>
      <div>
        <el-row align="middle">
          <el-tooltip placement="top">
            <template #content>{{ sensor.name }}</template>
            <text
              style="
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                margin-right: 10px;
              "
              truncated
              >{{ sensor.name }}</text
            >
          </el-tooltip>

          <el-button
            :disabled="expData.state == 20"
            style="margin-left: auto"
            @click="clickSetting(sensor, index)"
            :icon="Setting"
          />
          <el-button
            :disabled="expData.state == 20"
            @click="clickRun(sensor)"
            type="primary"
            :icon="VideoPlay"
          />
        </el-row>
      </div>
    </template>
    <el-descriptions :column="2">
      <template v-if="sensor.model == 'HnwDC1000'">
        <el-descriptions-item label="模式">
          <el-tag effect="light" :type="sensor.autoMode ? 'success' : ''">{{
            sensor.autoMode ? "自动" : "手动"
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前温度">
          <el-tag type="info"
            >{{ sensor.nowTemp }} ℃</el-tag
          ></el-descriptions-item
        >
        <el-descriptions-item :span="2" label="目标温度">
          <el-input-number
            v-model="sensor.temperature"
            :disabled="expData.state == 20"
            :min="0"
            :max="200"
            :precision="1"
            :step="0.1"
            size="small"
            controls-position="right"
            @change="changeVal"
          />℃
        </el-descriptions-item>
      </template>
      <template v-else-if="sensor.model == 'Valve'">
        <el-descriptions-item label="模式">
          <el-tag effect="light" :type="sensor.autoMode ? 'success' : ''">{{
            sensor.autoMode ? "自动" : "手动"
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前开度">
          <el-tag type="info"
            >{{ sensor.nowOpening }} %</el-tag
          ></el-descriptions-item
        >
        <el-descriptions-item :span="2" label="目标开度">
          <el-input-number
            :disabled="expData.state == 20"
            v-model="sensor.opening"
            :min="0"
            :max="200"
            :precision="1"
            :step="0.1"
            size="small"
            controls-position="right"
            @change="changeVal"
          />%
        </el-descriptions-item>
      </template>
    </el-descriptions>
  </el-card>
  <contordialog
    @data-confirm-click="$emit('data-confirm-click')"
    @delete-item="$emit('delete-item', $event)"
    v-model:visible="contorDialogVisible"
    :expData="expData"
    :tempControl="tempControl"
    v-model:controlList="controlListRef"
  />
</template>

<style lang="scss" scoped>
.main-content {
  margin: 8px !important;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: white;
}

.el-row {
  flex-wrap: nowrap !important;
}
</style>
